package com.ruoyi.project.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.ProjectContractDetail;
import com.ruoyi.system.service.IProjectContractDetailService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.domain.ProjectContract;
import com.ruoyi.project.service.IProjectContractService;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/project/projectContract")
public class ProjectContractController extends BaseController {

    @Autowired
    private IProjectContractService projectContractService;

    @Autowired
    private IProjectContractDetailService projectContractDetailService;

    @PostMapping("/upload")
    @PreAuthorize("@ss.hasPermi('project:projectContract:add')")
    @Log(title = "项目合同", businessType = BusinessType.INSERT)
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("contractId") Long contractId) throws IOException {
        if (!file.isEmpty()) {
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = FileUploadUtils.upload(filePath, file);
            String fileUrl = "/upload/" + fileName;

            ProjectContractDetail detail = new ProjectContractDetail();
            detail.setContractId(contractId);
            detail.setDetailUrl(fileUrl);

            // 检查是否存在已有的合同详情记录
            ProjectContractDetail existingDetail = projectContractDetailService.selectProjectContractDetailByContractId(contractId);
            if (existingDetail != null) {
                detail.setDetailId(existingDetail.getDetailId());
                projectContractDetailService.updateProjectContractDetail(detail);
            } else {
                projectContractDetailService.insertProjectContractDetail(detail);
            }

            return AjaxResult.success("文件上传成功").put("url", fileUrl);
        }
        return AjaxResult.error("文件上传失败");
    }


    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('project:projectContract:list')")
    public TableDataInfo list(ProjectContract projectContract) {
        startPage();
        List<ProjectContract> list = projectContractService.selectProjectContractList(projectContract);
        return getDataTable(list);
    }

    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermi('project:projectContract:export')")
    @Log(title = "项目合同", businessType = BusinessType.EXPORT)
    public void export(HttpServletResponse response, ProjectContract projectContract) {
        List<ProjectContract> list = projectContractService.selectProjectContractList(projectContract);
        ExcelUtil<ProjectContract> util = new ExcelUtil<>(ProjectContract.class);
        util.exportExcel(response, list, "项目合同数据");
    }

    @GetMapping("/{contractId}")
    @PreAuthorize("@ss.hasPermi('project:projectContract:query')")
    public AjaxResult getInfo(@PathVariable("contractId") Long contractId) {
        return success(projectContractService.selectProjectContractByContractId(contractId));
    }

    @PostMapping
    @PreAuthorize("@ss.hasPermi('project:projectContract:add')")
    @Log(title = "项目合同", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody ProjectContract projectContract) {
        int result = projectContractService.insertProjectContract(projectContract);
        if (result > 0) {
            return AjaxResult.success("新增成功", projectContract);
        } else {
            return AjaxResult.error("新增失败");
        }
    }

    @PutMapping
    @PreAuthorize("@ss.hasPermi('project:projectContract:edit')")
    @Log(title = "项目合同", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@RequestBody ProjectContract projectContract) {
        return toAjax(projectContractService.updateProjectContract(projectContract));  
    }

    @DeleteMapping("/{contractIds}")
    @PreAuthorize("@ss.hasPermi('project:projectContract:remove')")
    @Log(title = "项目合同", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable Long[] contractIds) {
        projectContractService.deleteByContractIds(contractIds);
        return toAjax(projectContractService.deleteProjectContractByContractIds(contractIds));
    }
}
